<?php


namespace App\Http\Services\Admin;


use App\Http\Constants\JobsConstants;
use App\Models\FailedJobs;
use App\Models\Jobs;
use YiluTech\ComplexSearch\ComplexSearch;

class JobsService extends ComplexSearch
{
    public $root = Jobs::class;

    protected $display = 'simple';
    protected $orderBy = 'id desc';

    protected $headers = [
        ['value' => 'id', 'label' => '序号'],
        ['value' => 'queue', 'label' => '名称'],
        ['value' => 'payload', 'label' => '数据'],
        ['value' => 'available_at', 'label' => '执行时间'],
        ['value' => 'create_at', 'label' => '创建时间'],
    ];

    protected $conditions = [
        'queue' => [
            'label' => '队列类型',
            'ctype' => 'select',
            'operator' => JobsConstants::QUEUE,
        ],
        'created_at' => [
            'label' => '创建时间',
            'ctype' => 'date-in',
            'format' => 'Y-m-d',
            'display' => true
        ]
    ];

    public function query()
    {
        $query = parent::query();
        if ($this->action != 'prepare') {
            $query->select('id', 'queue', 'payload', 'available_at', 'created_at', 'attempts', 'reserved_at');
        }
        return $query;
    }


    public function statistics()
    {

        $pendingNumber = Jobs::where('attempts', 0)
            ->count();
        $pendingRetryNumber = Jobs::where('attempts', '>' ,0)
            ->count();
        $failedNumber = FailedJobs::count();
        $result = [
            'pending_number' => $pendingNumber,
            'pending_retry_number' => $pendingRetryNumber,
            'failed_number' => $failedNumber,
        ];
        return $result;
    }

}
